class MyPromise {
  constructor(executor) {
    this.status = "pending"; // 初始状态
    this.value = undefined; // 成功值
    this.reason = undefined; // 失败原因

    this.onFulfilledCallbacks = []; // 成功回调队列
    this.onRejectedCallbacks = []; // 失败回调队列

    const resolve = (value) => {
      if (this.status === "pending") {
        this.status = "fulfilled";
        this.value = value;
        this.onFulfilledCallbacks.forEach((fn) => fn(value));
      }
    };

    const reject = (reason) => {
      if (this.status === "pending") {
        this.status = "rejected";
        this.reason = reason;
        this.onRejectedCallbacks.forEach((fn) => fn(reason));
      }
    };

    try {
      executor(resolve, reject);
    } catch (err) {
      reject(err);
    }
  }

  then(onFulfilled, onRejected) {
    // 如果没有传回调，就用默认透传
    onFulfilled = typeof onFulfilled === "function" ? onFulfilled : (v) => v;
    onRejected =
      typeof onRejected === "function"
        ? onRejected
        : (err) => {
            throw err;
          };

    return new MyPromise((resolve, reject) => {
      if (this.status === "fulfilled") {
        setTimeout(() => {
          // 异步执行
          try {
            const x = onFulfilled(this.value);
            resolve(x);
          } catch (err) {
            reject(err);
          }
        }, 0);
      } else if (this.status === "rejected") {
        setTimeout(() => {
          try {
            const x = onRejected(this.reason);
            resolve(x);
          } catch (err) {
            reject(err);
          }
        }, 0);
      } else if (this.status === "pending") {
        // 先存起来，状态改变再执行
        this.onFulfilledCallbacks.push((value) => {
          setTimeout(() => {
            try {
              const x = onFulfilled(value);
              resolve(x);
            } catch (err) {
              reject(err);
            }
          }, 0);
        });

        this.onRejectedCallbacks.push((reason) => {
          setTimeout(() => {
            try {
              const x = onRejected(reason);
              resolve(x);
            } catch (err) {
              reject(err);
            }
          }, 0);
        });
      }
    });
  }
}
new MyPromise((resolve, reject) => {
  resolve("OK");
}).then((res) => {
  console.log("同步 resolve ->", res);
});

new MyPromise((resolve) => resolve(1))
  .then((res) => {
    console.log("第1个 then ->", res);
    return res + 1;
  })
  .then((res) => {
    console.log("第2个 then ->", res);
    return res + 1;
  })
  .then((res) => console.log("第3个 then ->", res));
